package com.tsfyun.scm.service.impl.user;

import cn.hutool.core.lang.Snowflake;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.scm.entity.user.PersonRole;
import com.tsfyun.scm.mapper.user.PersonRoleMapper;
import com.tsfyun.scm.service.user.IPersonRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PersonRoleServiceImpl extends ServiceImpl<PersonRole> implements IPersonRoleService {

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private PersonRoleMapper personRoleMapper;

    @Override
    public List<PersonRole> getPersonRoles(Long personId) {
        PersonRole condition = new PersonRole();
        condition.setPersonId(personId);
        return super.list(condition);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Long personId, List<String> roleIdList) {
        //先解除员工和角色的关系
        PersonRole personRole = new PersonRole();
        personRole.setPersonId(personId);
        super.remove(personRole);

        if(roleIdList == null || roleIdList.size() == 0){
            return ;
        }
        //保存员工与角色关系
        //对id去重
        roleIdList = roleIdList.stream().distinct().collect(Collectors.toList());
        List<PersonRole> list = new ArrayList<>();
        for(String roleId : roleIdList){
            PersonRole savePersonRole = new PersonRole();
            savePersonRole.setId(snowflake.nextId());
            savePersonRole.setPersonId(personId);
            savePersonRole.setRoleId(roleId);
            savePersonRole.setDateCreated(LocalDateTime.now());
            savePersonRole.setDateUpdated(savePersonRole.getDateCreated());
            savePersonRole.setCreateBy(SecurityUtil.getCurrentPersonIdAndName());
            savePersonRole.setUpdateBy(savePersonRole.getCreateBy());
            list.add(savePersonRole);
        }
        try {
            super.savaBatch(list);
        } catch (DataIntegrityViolationException e) {
            throw new ServiceException("选择的角色数据不存在");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteBatchByRoleIds(List<String> roleIds) {
        return personRoleMapper.deleteBatchByRoleIds(roleIds);
    }

}
